from mysqldb.header import *
from .serializers import *


from mysqldb.ismobile import judge_pc_or_mobile
import logging

logger = logging.getLogger(__name__)
# serializer.validated_data 验证后的数据
# Create your views here.


class WeChatLoginViewSet(viewsets.ModelViewSet):
    __title__ = "微信登录"
    __group__ = "微信模块"
    __info__ = {"post": "微信登录"}
    __doc__ = """
    create:\n
    <h4>微信登录</h4>
        老用户登录
    """
    http_method_names = ["post"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    serializer_class = WeChatLoginSerializer
    queryset = AllinpayStaffList.objects.all()

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        # 请求腾讯
        WX = requests_SDK()
        WX.getConf()
        code = serializer.data.get("code")
        headers = WX.has_headers()
        headers["Content-Type"] = "application/json"
        params = {
            "appid": WX.Conf.get("appid"),
            "secret": WX.Conf.get("secret"),
            "js_code": code,
            "grant_type": "authorization_code",
        }
        r = WX.do_get("/sns/jscode2session", headers=headers, params=params)
        if not r or r.get("errcode"):
            raise serializers.ValidationError({"jscode2session": "微信小程序接口错误"})

        print(r)

        # 检测员工
        try:
            Staff = self.get_queryset().get(openid=r.get("openid"))
            # Staff = self.get_queryset().get(unid=r.get("unionid"))
        except BaseException as err:
            return Response({"rescode": 400, "resmsg": r, "token": None})
        else:
            if not Staff.status:
                raise serializers.ValidationError({"status": "用户已禁用"})
            Staff.unid = r.get("unionid")
            Staff.modifed = timezone.now()
            Staff.save()

        # 创建Token
        Token = get_tokens_for_user(Staff)
        return Response(
            {"rescode": 200, "resmsg": r, "token": Token, "staffID": Staff.id}
        )


class WeChatLoginPhoneViewSet(viewsets.ModelViewSet):
    __title__ = "微信手机登录"
    __group__ = "微信模块"
    __info__ = {"post": "微信手机登录"}
    __doc__ = """
    create:\n
    <h4>微信手机登录</h4>
        新用户注册
    """
    http_method_names = ["post"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    serializer_class = WeChatMobleSerializer
    queryset = AllinpayStaffList.objects.all()

    def create(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        openid = serializer.data.get("openid")
        unid = serializer.data.get("unid")

        WX = requests_SDK()
        WX.getConf()

        # Access_token
        Access_token = WX.has_access_token()
        if not Access_token:
            logger.warn(f"[Staff_REG] 获取小程序Token失败!")
            raise serializers.ValidationError({"Access_token": "内部错误"})

        # 请求数据
        code = serializer.data.get("code")
        headers = WX.has_headers()
        headers["Content-Type"] = "application/json"
        params = {
            "access_token": Access_token,
        }
        data = {"code": code}
        r = WX.do_post(
            "/wxa/business/getuserphonenumber",
            headers=headers,
            params=params,
            json=data,
        )
        if not r or r.get("errcode"):
            logger.warn(f"[Staff_REG] 查询员工手机号失败!")
            raise serializers.ValidationError({"phonenumber": "查询手机号码失败"})
        try:
            phone = r.get("phone_info").get("purePhoneNumber")
        except BaseException as err:
            logger.warn(f"[Staff_REG] 获取员工手机号失败!")
            raise serializers.ValidationError({"phone": f"获取手机失败:{err}"})
        # 检测员工
        try:
            Staff = self.get_queryset().get(phone=phone)
        except AllinpayStaffList.DoesNotExist as err:
            logger.warn(f"[Staff_REG] 创建新员工 {phone}")
            Staff = AllinpayStaffList(
                phone=phone,
                openid=openid,
                unid=unid,
                status=1,
                created=timezone.now(),
                modifed=timezone.now(),
            )
            Staff.save()
        # 登录员工
        if not Staff.status:
            raise serializers.ValidationError({"status": "用户已禁用"})
        Staff.openid = openid
        Staff.unid = unid
        Staff.modifed = timezone.now()
        Staff.save()

        # 创建Token
        Token = get_tokens_for_user(Staff)
        return Response({"rescode": 200, "resmsg": r, "token": Token})


class WeChatStaffBindViewSet(viewsets.ModelViewSet):
    __title__ = "账户绑定微信"
    __group__ = "微信模块"
    __info__ = {"post": "手机账户绑定微信"}
    __doc__ = """
    create:\n
    <h4>手机账户绑定微信</h4>
    """
    http_method_names = ["post"]
    authentication_classes = [WeChatJWTAuthentication]
    permission_classes = [WeChatPermissions]
    serializer_class = WeChatStaffBindSerializer
    queryset = AllinpayStaffList.objects.all()

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        instance = request.user
        try:
            instance.phone = serializer.data["phone"]
            instance.openid = serializer.data["openid"]
            instance.unid = serializer.data["unid"]
            instance.modifed = timezone.now()
            instance.save()
        except BaseException as err:
            raise serializers.ValidationError({"Staff": "绑定失败"})
        else:
            # 发送消息队列
            # place_list = AllinpayPlacestaffList.objects.filter(
            #     sid=instance.id
            # ).values_list("pid", flat=True)
            # for pid in list(place_list):
            #     SendAsyncMessage(
            #         pid, "AllinpayStaffList", f"/staff/allstaff/{instance.id}/"
            #     )
            pass
        return Response({"rescode": 200, "resmsg": serializer.data})


class WeChatStaffListViewSet(viewsets.ModelViewSet):
    __title__ = "微信员工信息"
    __group__ = "微信模块"
    __info__ = {"get": "微信员工信息列表或详情", "put": "编辑微信员工个人信息"}
    __doc__ = """
    list:\n
    <h4>微信员工信息列表</h4>
    retrieve:\n
    <h4>微信员工信息详情</h4>
        {id} 该值可以任意填写，不可空。
    update:\n
    <h4>编辑微信员工个人信息</h4>
        {id} 该值可以任意填写，不可空。
    """
    http_method_names = ["get", "put"]
    authentication_classes = [WeChatJWTAuthentication]
    permission_classes = [WeChatPermissions]
    serializer_class = WeChatAllinpayStaffListSerializer
    queryset = AllinpayStaffList.objects.all()
    filter_backends = [MyFilterBackend, MySearchBackend]
    filterset_fields = ["status"]
    search_fields = ["basename", "phone"]

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def retrieve(self, request, *args, **kwargs):
        instance = request.user
        serializer = self.get_serializer(instance)
        return Response(
            {
                "rescode": 200,
                "resmsg": serializer.data,
            }
        )

    def update(self, request, *args, **kwargs):
        partial = False
        # instance = self.get_object()
        instance = request.user
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        # 发送消息队列
        # place_list = AllinpayPlacestaffList.objects.filter(sid=instance.id).values_list(
        #     "pid", flat=True
        # )
        # for pid in list(place_list):
        #     SendAsyncMessage(
        #         pid, "AllinpayStaffList", f"/staff/allstaff/{instance.id}/"
        #     )
        return Response({"rescode": 200, "resmsg": serializer.data})


class WeChatAllinpayPlaceListViewSet(viewsets.ModelViewSet):
    __title__ = "微信场所列表"
    __group__ = "微信模块"
    __info__ = {"get": "微信场所列表或详情", "post": "注册场所", "put": "编辑场所信息"}
    __doc__ = """
    list:\n
    <h4>微信场所列表</h4>
    retrieve:\n
    <h4>微信场所详情</h4>
    create:\n
    <h4>注册场所</h4>
    update:\n
    <h4>编辑场所信息</h4>
    """
    http_method_names = ["get", "put"]
    authentication_classes = [WeChatJWTAuthentication]
    permission_classes = [WeChatPermissions]
    serializer_class = WeChatAllinpayPlaceListSerializer
    queryset = AllinpayPlaceList.objects.all()
    filter_backends = [MyFilterBackend, MySearchBackend]
    filterset_fields = ["sheng", "shi", "xian", "status", "auth", "fee"]
    search_fields = ["basename", "name", "addr", "telephone"]

    def list(self, request, *args, **kwargs):
        place_list = AllinpayPlacestaffList.objects.filter(
            sid=request.user.id
        ).values_list("pid", flat=True)
        queryset = self.filter_queryset(
            self.get_queryset().filter(status=1).exclude(id__in=list(place_list))
        )
        serializer = self.get_serializer(queryset, many=True)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def update(self, request, *args, **kwargs):
        partial = False
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        # 发送消息队列
        # SendAsyncMessage(
        #     instance.id, "AllinpayPlaceInfo", f"/place/battrs/{instance.id}/"
        # )

        return Response({"rescode": 200, "resmsg": serializer.data})


class WeChatAllinpayPlacestaffListViewSet(viewsets.ModelViewSet):
    __title__ = "微信绑定员工到场所列表"
    __group__ = "微信模块"
    __info__ = {"get": "微信绑定员工到场所列表或详情"}
    __doc__ = """
    list:\n
    <h4>微信绑定员工到场所列表</h4>
    retrieve:\n
    <h4>微信绑定员工到场所详情</h4>
    """
    http_method_names = ["get"]
    authentication_classes = [WeChatJWTAuthentication]
    permission_classes = [WeChatPermissions]
    serializer_class = WeChatAllinpayPlacestaffListSerializer
    queryset = AllinpayPlacestaffList.objects.all()
    filter_backends = [MyFilterBackend]
    filterset_fields = ["status", "sid", "pid"]

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})


class WeChatBindPlaceViewSet(viewsets.ModelViewSet):
    __title__ = "微信绑定员工到场所请求"
    __group__ = "微信模块"
    __info__ = {"get": "微信绑定员工到场所请求"}
    __doc__ = """
    list:\n
    <h4>停用</h4>
    retrieve:\n
    <h4>微信绑定员工到场所请求</h4>
        {id} 场所ID
    `该接口用于生成二维码供员工扫码请求`
    """
    http_method_names = ["get"]
    authentication_classes = [WeChatJWTAuthentication]
    permission_classes = [WeChatPermissions]
    serializer_class = NoneSerializer
    queryset = AllinpayPlaceList.objects.all()

    def list(self, request, *args, **kwargs):
        raise serializers.ValidationError({"status": "该接口已停用"})
        # queryset = self.filter_queryset(self.get_queryset())
        # serializer = self.get_serializer(queryset, many=True)
        # return Response({"rescode": 200, "resmsg": serializer.data})

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        if not instance.status:
            raise serializers.ValidationError({"status": "该场所已停用"})
        try:
            Bind = AllinpayPlacestaffList.objects.get(
                sid=request.user.id, pid=instance.id
            )
        except BaseException as err:
            Bind = AllinpayPlacestaffList(
                sid=request.user.id, pid=instance.id, created=timezone.now(), status=0
            )
            Bind.save()
            # 发送消息队列
            # SendAsyncMessage(
            #     instance.id, "AllinpayPlacestaffList", f"/staff/allstaff/{Bind.id}/"
            # )
        AllinpayPlacestaffExtend.objects.update_or_create(
            defaults={"modifed": timezone.now(), "mobile": 1, "platform": 1}, id=Bind.id
        )
        serializer = WeChatAllinpayPlacestaffListSerializer(Bind)
        return Response({"rescode": 200, "resmsg": serializer.data})


class WeChatBindPlaceActViewSet(viewsets.ModelViewSet):
    __title__ = "微信绑定员工到场所请求审核"
    __group__ = "微信模块"
    __info__ = {"put": "微信绑定员工到场所请求审核"}
    __doc__ = """
    update:\n:\n
    <h4>微信绑定员工到场所请求审核</h4>
    """
    http_method_names = ["put"]
    authentication_classes = [WeChatJWTAuthentication]
    permission_classes = [WeChatPermissions]
    serializer_class = WeChatAllinpayPlacestaffActSerializer
    queryset = AllinpayPlacestaffList.objects.all()

    def update(self, request, *args, **kwargs):
        partial = False
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        # 创建扩展信息
        AllinpayPlacestaffExtend.objects.update_or_create(
            defaults={"modifed": timezone.now(), "mobile": 1, "platform": 1},
            id=instance.id,
        )
        # 创建员工上岗
        AllinpayPlacestaffPost.objects.update_or_create(
            defaults={"status": 0}, id=instance.id
        )
        # 发送消息队列
        # SendAsyncMessage(
        #     instance.pid, "AllinpayPlacestaffList", f"/staff/allstaff/{instance.id}/"
        # )
        # SendAsyncMessage(
        #     instance.pid, "AllinpayPlacestaffExtend", f"/place/staffextd/{instance.id}/"
        # )
        # SendAsyncMessage(
        #     instance.pid, "AllinpayPlacestaffPost", f"/place/staffpost/{instance.id}/"
        # )
        return Response({"rescode": 200, "resmsg": serializer.data})


class WeChatChangePlaceViewSet(viewsets.ModelViewSet):
    __title__ = "员工切换场所"
    __group__ = "微信模块"
    __info__ = {"put": "员工切换场所"}
    __doc__ = """
    update:\n:\n
    <h4>微信登录场所</h4>
        {id} 场所ID
    """
    http_method_names = ["put"]
    authentication_classes = [WeChatJWTAuthentication, BarJWTAuthentication]

    permission_classes = [WeChatPermissions | BarPermissions]

    serializer_class = NoneSerializer
    queryset = AllinpayPlacestaffList.objects.all()

    def update(self, request, *args, **kwargs):
        ua = request.META.get("HTTP_USER_AGENT")
        mobile = judge_pc_or_mobile(ua)
        pk = kwargs.get("pk")
        try:
            place = AllinpayPlaceList.objects.get(id=pk, status=1)
            instance = self.queryset.get(pid=place.id, sid=request.user.id, status=1)
            extend = AllinpayPlacestaffExtend.objects.get(id=instance.id)
        except AllinpayPlaceList.DoesNotExist as err:
            raise serializers.ValidationError({"Place": "该场所已停用"})
        except AllinpayPlacestaffList.DoesNotExist as err:
            raise serializers.ValidationError({"PlaceStaff": "禁止切换该场所"})
        except AllinpayPlacestaffExtend.DoesNotExist as err:
            raise serializers.ValidationError({"PlacestaffExtend": "禁止切换该场所,缺少员工技能信息"})
        except BaseException as err:
            raise serializers.ValidationError({"BaseError": f"禁止切换该场所 {err}"})
        else:
            if mobile and not extend.mobile:
                raise serializers.ValidationError({"mobile": "禁止移动端切换该场所"})
            if not mobile and not extend.platform:
                raise serializers.ValidationError({"platform": "禁止PC端切换该场所"})

        partial = True
        serializer = WeChatAllinpayPlacestaffListSerializer(
            instance, data={"modifed": timezone.now()}, partial=partial
        )
        serializer.is_valid(raise_exception=True)
        serializer.save()

        # request.placeID = place.id
        # request.PlaceStaff = instance.id

        # 写入缓存,供权限验证
        REDIS.redis_key_set("loginPlace", request.user.id, pk)

        # 调取呼叫配置
        Callme = AllinpayCallmeConf.objects.filter(pid=place.id).values(
            "id",
            "name",
            "status",
            "timeout",
            "dispatch",
            "le0",
            "le1",
            "le2",
            "le3",
            "le4",
            "le5",
            "appurl",
        )
        # 调取员工在岗
        try:
            Post = AllinpayPlacestaffPost.objects.get(id=instance.id).status
        except BaseException as err:
            Post = 0
        x = serializer.data.copy()
        x["CallmeConf"] = Callme
        x["barcode"] = place.barcode
        x["OnPost"] = Post
        return Response({"rescode": 200, "resmsg": x})


class WeChatWeChatPlaceStaffExtendViewSet(viewsets.ModelViewSet):
    __title__ = "微信场所员工扩展信息列表"
    __group__ = "微信模块"
    __info__ = {"get": "微信场所员工扩展信息列表", "put": "编辑微信场所员工扩展信息"}
    __doc__ = """
    list:\n
    <h4>微信场所员工扩展列表</h4>
    retrieve:\n
    <h4>微信场所员工扩展信息</h4>
    update:\n
    <h4>微信场所员工扩展信息</h4>
        {id} 场所绑定ID
    """
    http_method_names = ["get", "put"]
    authentication_classes = [MyJWTAuthentication, WeChatJWTAuthentication]
    permission_classes = [MyPermissions | WeChatPermissions]
    serializer_class = WeChatPlaceStaffExtendSerializer
    queryset = AllinpayPlacestaffExtend.objects.all()

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def update(self, request, *args, **kwargs):
        pk = kwargs.get("pk")
        try:
            partial = True
            instance = self.get_object()
            serializer = self.get_serializer(
                instance, data=request.data, partial=partial
            )
            serializer.is_valid(raise_exception=True)
            serializer.save(modifed=timezone.now())
        except BaseException as err:
            instance, faq = AllinpayPlacestaffExtend.objects.update_or_create(
                defaults=request.data, id=pk
            )
            serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})


class WeChatBindPermActViewSet(viewsets.ModelViewSet):
    __title__ = "微信聚合查询角色权限列表"
    __group__ = "微信模块"
    __info__ = {"post": "微信聚合查询角色权限列表"}
    __doc__ = """
    create:\n
    <h4>微信聚合查询角色权限列表</h4>
        id: 视图ID
        status： 权限记录ID, > 0 拥有该权限
        staff：视图类型
    """
    http_method_names = ["post"]
    authentication_classes = [MyJWTAuthentication, WeChatJWTAuthentication]
    permission_classes = [MyPermissions | WeChatPermissions]
    serializer_class = MiniSerializer
    queryset = AllinpayAuthViews.objects.all()

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        # ========================
        # 角色ID
        # ========================
        rid = serializer.data.get("rid")
        try:
            sess = AllinpayPlaceroleList.objects.get(id=rid)
        except BaseException as err:
            raise serializers.ValidationError({"Role": "未找到该角色"})
        else:
            sess = model_to_dict(sess)
        # ========================
        # 吧台端权限
        # ========================
        q = AllinpayAuthViews.objects.filter(staff__in=[2, 3]).annotate(
            rid=Value(rid, output_field=intf())
        )
        # ========================
        # 移动端权限
        # ========================
        r = AllinpayAuthViews.objects.filter(staff__in=[1, 3]).annotate(
            rid=Value(rid, output_field=intf())
        )
        # ========================
        # 员工权限
        # ========================
        s = AllinpayAuthViews.objects.filter(staff__gt=0).annotate(
            rid=Value(rid, output_field=intf())
        )
        
        # ========================
        # 新因数查询
        # ========================
        y = AllinpayAuthViews.objects.filter(staff__in=self.has_Chmod(2)).annotate(
            rid=Value(rid, output_field=intf())
        )       
        return Response(
            {
                "rescode": 200,
                "resmsg": sess,
                "place": WeChatAuthViewsListSerializer(y, many=True).data,  # 吧台端
                "yun": WeChatAuthViewsListSerializer(y, many=True).data,  # 移动端
                "staff": WeChatAuthViewsListSerializer(y, many=True).data,  # 员工端
            }
        )
    def has_Chmod(self, staff):
        """返回包含指定因子的数列"""
        return [i for i in range(settings.PLACE_CHMOD_LIST.__len__()) if staff in settings.PLACE_CHMOD_LIST[i]] 

class WeChatBindPermChangViewSet(viewsets.ModelViewSet):
    __title__ = "微信设置角色场所权限列表"
    __group__ = "微信模块"
    __info__ = {"post": "微信设置角色场所权限", "delete": "微信移除角色场所权限"}
    __doc__ = """
    create:\n
    <h4>微信设置角色场所权限</h4>
    delete:\n
    <h4>微信移除角色场所权限</h4>
        {id} 绑定记录ID
    """
    http_method_names = ["post", "delete"]
    authentication_classes = [WeChatJWTAuthentication]
    permission_classes = [WeChatPermissions]
    serializer_class = WeChatAllinpayPlaceRolePermSerializer
    queryset = AllinpayPlacerolePerm.objects.all()
    filter_backends = [MyFilterBackend]
    filterset_fields = ["rid"]

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        # 发送消息队列
        # SendAsyncMessage(
        #     request.placeID,
        #     "AllinpayPlacerolePerm",
        #     f'/place/roleperms/{serializer.data.get("id")}/',
        # )
        return Response({"rescode": 200, "resmsg": serializer.data})

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        kid = instance.id
        self.perform_destroy(instance)
        # 发送消息队列
        # SendAsyncMessage(request.placeID, "AllinpayPlacerolePerm", kid, "delete")
        return Response({"rescode": 200, "resmsg": "SUCCESS"})


class WeChatBindPermYunViewSet(viewsets.ModelViewSet):
    __title__ = "微信设置角色云端权限列表"
    __group__ = "微信模块"
    __info__ = {"post": "微信设置角色云端权限", "delete": "微信移除角色云端权限"}
    __doc__ = """
    create:\n
    <h4>微信设置角色云端权限</h4>
    delete:\n
    <h4>微信移除角色云端权限</h4>
        {id} 绑定记录ID
    """
    http_method_names = ["post", "delete"]
    authentication_classes = [WeChatJWTAuthentication]
    permission_classes = [WeChatPermissions]
    serializer_class = WeChatAllinpayPlaceRolePermYunSerializer
    queryset = AllinpayPlacerolePermYun.objects.all()
    filter_backends = [MyFilterBackend]
    filterset_fields = ["rid"]

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({"rescode": 200, "resmsg": serializer.data})

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        kid = instance.id
        self.perform_destroy(instance)
        return Response({"rescode": 200, "resmsg": "SUCCESS"})


class WeChatAllinpayPlaceRoleListViewSet(viewsets.ModelViewSet):
    __title__ = "微信角色列表"
    __group__ = "微信模块"
    __info__ = {"get": "微信角色列表或详情", "post": "微信创建角色", "put": "微信编辑角色"}
    __doc__ = """
    list:\n
    <h4>微信角色列表</h4>
    retrieve:\n
    <h4>微信角色详情</h4>
    create:\n
    <h4>微信创建角色</h4>
    update:\n
    <h4>微信编辑角色</h4>
    """
    http_method_names = ["post", "get", "put"]
    authentication_classes = [WeChatJWTAuthentication]
    permission_classes = [WeChatPermissions]
    serializer_class = WeChatAllinpayPlaceRoleListSerializer
    queryset = AllinpayPlaceroleList.objects.all()
    filter_backends = [MyFilterBackend]
    filterset_fields = ["pid"]

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        # 发送消息队列
        # SendAsyncMessage(
        #     request.placeID,
        #     "AllinpayPlaceroleList",
        #     f'/place/myrole/{serializer.data.get("id")}/',
        # )
        return Response({"rescode": 200, "resmsg": serializer.data})

    def update(self, request, *args, **kwargs):
        partial = False
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        # 发送消息队列
        # SendAsyncMessage(
        #     request.placeID,
        #     "AllinpayPlaceroleList",
        #     f'/place/myrole/{serializer.data.get("id")}/',
        # )
        return Response({"rescode": 200, "resmsg": serializer.data})


class WeChatPlaceStaffRoleListViewSet(viewsets.ModelViewSet):
    __title__ = "微信员工角色分配列表"
    __group__ = "微信模块"
    __info__ = {"get": "微信员工角色分配列表或详情", "post": "微信员工角色分配创建", "delete": "微信员工角色分配移除"}
    __doc__ = """
    list:\n
    <h4>微信员工角色分配列表</h4>
    retrieve:\n
    <h4>微信员工角色分配详情</h4>
    create:\n
    <h4>微信员工角色分配创建</h4>
    delete:\n
    <h4>微信员工角色分配移除</h4>
    """
    http_method_names = ["get", "post", "delete"]
    authentication_classes = [WeChatJWTAuthentication]
    permission_classes = [WeChatPermissions]
    serializer_class = WeChatAllinpayPlacestaffRoleSerializer
    queryset = AllinpayPlacestaffRole.objects.all()
    filter_backends = [MyFilterBackend]
    filterset_fields = ["pid", "sid", "rid"]

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        serializer = self.get_serializer(queryset, many=True)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        # 发送消息队列
        # SendAsyncMessage(
        #     request.placeID,
        #     "AllinpayPlacestaffRole",
        #     f'/place/staffrole/{serializer.data.get("id")}/',
        # )
        return Response({"rescode": 200, "resmsg": serializer.data})

    def destroy(self, request, *args, **kwargs):
        instance = self.get_object()
        kid = instance.id
        self.perform_destroy(instance)
        # 发送消息队列
        # SendAsyncMessage(request.placeID, "AllinpayPlacestaffRole", kid, "delete")
        return Response({"rescode": 200, "resmsg": "SUCCESS"})


class WeChatNewRolePermsViewSet(viewsets.ModelViewSet):
    __title__ = "微信角色吧台端权限分配"
    __group__ = "微信模块"
    __info__ = {"post": "微信角色场所权限分配"}
    __doc__ = """
    create:\n
    <h4>微信角色场所权限分配</h4>
        请求参数:
        [{"rid":1,"vid":1,"status":0}...]
    """
    http_method_names = ["post"]
    authentication_classes = [MyJWTAuthentication, WeChatJWTAuthentication]
    permission_classes = [MyPermissions | WeChatPermissions]
    serializer_class = WeChatNewRolePlacePermsSerializer
    queryset = AllinpayPlacerolePerm.objects.all()

    # filter_backends = [MyFilterBackend]
    # filterset_fields = ["rid"]

    def create(self, request, *args, **kwargs):
        # print(request.data)
        serializer = self.get_serializer(None, data=request.data, many=True)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({"rescode": 200, "resmsg": serializer.data})


class WeChatNewRoleYunPermsViewSet(viewsets.ModelViewSet):
    __title__ = "微信角色移动端权限分配"
    __group__ = "微信模块"
    __info__ = {"post": "微信角色云端权限分配"}
    __doc__ = """
    create:\n
    <h4>微信角色云端权限分配</h4>
        请求参数:
        [{"rid":1,"vid":1,"status":0}...]
    """
    http_method_names = ["post"]
    authentication_classes = [MyJWTAuthentication, WeChatJWTAuthentication]
    permission_classes = [MyPermissions | WeChatPermissions]
    serializer_class = WeChatNewRoleMobilePermsSerializer
    queryset = AllinpayPlacerolePermYun.objects.all()

    # filter_backends = [MyFilterBackend]
    # filterset_fields = ["rid"]

    def create(self, request, *args, **kwargs):
        # print(request.data)
        serializer = self.get_serializer(None, data=request.data, many=True)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({"rescode": 200, "resmsg": serializer.data})


class SendUniformMessageViewSet(viewsets.ModelViewSet):
    __title__ = "微信统一消息测试"
    __group__ = "微信模块"
    __info__ = {"post": "微信统一消息测试"}
    __doc__ = """
    create:\n
    <h4>微信统一消息测试</h4>
        发送员工消息
    """
    http_method_names = ["post", "get"]
    authentication_classes = []
    permission_classes = [AllPermissions]
    serializer_class = WeChatMessageSerializer
    queryset = AllinpayCallmeList.objects.all()

    def list(self, request, *args, **kwargs):
        # queryset = self.filter_queryset(self.get_queryset())
        # serializer = self.get_serializer(queryset, many=True)
        ua = request.META.get("HTTP_USER_AGENT")
        mobile = judge_pc_or_mobile(ua)
        print(mobile)
        return Response({"rescode": 200, "resmsg": mobile})

    def retrieve(self, request, *args, **kwargs):
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return Response({"rescode": 200, "resmsg": serializer.data})

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        try:
            r = AllinpayStaffList.objects.get(phone=serializer.data.get("phone"))
        except BaseException as err:
            print(err)
            raise serializers.ValidationError("员工不存在")

        touser = r.openid
        path = "LoginBefor/callOrder/callOrder"
        modelname = "收到客户新订单通知"
        sargs = [
            "Test123456789",
            "作业项提醒",
            f'网思科技 {serializer.data.get("info")}',
            time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
        ]

        from mysqldb.tasks import WeAppsUniformSend

        res = WeAppsUniformSend.apply_async(
            (
                touser,
                path,
                modelname,
                sargs,
            )
        ).task_id

        return Response({"rescode": 200, "resmsg": res})


# 检查视图
filter_views(globals())
